//
//  NSString+MimeType.m
//  QTCategory
//
//  Created by 张俊博 on 16/9/11.
//  Copyright © 2016年 CISDI. All rights reserved.
//

#import "NSString+MimeType.h"
#import "NSBundle+QTAdd.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "QTCategoryMacro.h"

@interface MIMEMapping : NSObject

@property (nonatomic, strong)  NSDictionary   *mapTable;

+(MIMEMapping *)shareMapping;

- (NSString *)mimeTypeForExtension:(NSString *)extension;
- (NSString *)extensionFromMimeType:(NSString *)mimeType;

@end

@implementation MIMEMapping

+(MIMEMapping *)shareMapping{
    static MIMEMapping *mimeMapping = nil;
    static dispatch_once_t  predicate;
    
    dispatch_once(&predicate, ^{
        mimeMapping =[[MIMEMapping alloc] init];
    });
    
    return mimeMapping;
}


- (NSString *)mimeTypeForExtension:(NSString *)extension{
    
    if (isNullStr(extension)) {
        return @"application/octet-stream";
    }
    
    if (!self.mapTable) {
        self.mapTable = [self parseMIMETable];
    }
    
    NSString *key = [@"." stringByAppendingString:extension];
    
    NSString *value = [self.mapTable objectForKey:key];
    
    if (!value) {
        value = @"application/octet-stream";
    }
    
    return value;
}

- (NSString *)extensionFromMimeType:(NSString *)mimeType {
    if (!self.mapTable) {
        self.mapTable = [self parseMIMETable];
    }
    
    __block NSString *extension;
    [self.mapTable enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        if ([obj isEqualToString:mimeType]) {
            extension = key;
            *stop = YES;
        }
    }];
    
    if (extension) {
        extension = [extension stringByReplacingOccurrencesOfString:@"." withString:@""];
    }
    
    return extension;
}

- (NSDictionary *)parseMIMETable{
    NSString *filePath = [[NSBundle QTBundleWithName:@"QTCategoryBundle"] pathForResource:@"MIMETypeTable" ofType:@"txt"];
    
    NSString *fileContent = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    
    NSArray *components = [fileContent componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"{}"]];
    
    NSMutableDictionary *mapTable = [NSMutableDictionary dictionary];
    
    for (NSString *component in components) {
        
        NSArray *parsedComponent = [self parseComponent:component];
        
        if (parsedComponent) {
            NSString *key = [parsedComponent firstObject];
            NSString *value = [parsedComponent lastObject];
            
            [mapTable setObject:value forKey:key];
        }
    }
    
    return mapTable;
    
}

- (NSArray *)parseComponent:(NSString *)component{
    
    
    component = [component stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    if (component.length == 0) {
        return nil;
    }
    
    NSArray *subComponents = [component componentsSeparatedByString:@","];
    
    NSString *key = [[subComponents objectAtIndex:0] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSString *value = [[subComponents objectAtIndex:1] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    key = [key stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"\""]];
    value = [value stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"\""]];
    
    if (key != nil && key.length != 0 && value != nil && value.length != 0) {
        return @[key,value];
    }
    
    return nil;
}


@end

@implementation NSString (MimeType)

+(NSString *)mimeTypeForExtension:(NSString *)extension{
    
    extension = [extension lowercaseString];
    MIMEMapping *mapping = [MIMEMapping shareMapping];
    NSString *mimeType = [mapping mimeTypeForExtension:extension];
    
//    CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)extension, NULL);
//    CFStringRef MIMEType = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType);
//    CFRelease(UTI);
//    NSString *mimeType = @"application/octet-stream";
//    if (MIMEType) {
//        mimeType = (__bridge NSString *)(MIMEType);
//    } 
    
    return mimeType;
    
}

+(NSString *)extensionFromMimeType:(NSString *)mimeType {
    mimeType = [mimeType lowercaseString];
    MIMEMapping *mapping = [MIMEMapping shareMapping];
    NSString *extension = [mapping extensionFromMimeType:mimeType];
    
    return extension;
}

+ (BOOL)isImageForMimeType:(NSString *)mimeType {
    return mimeType && ([mimeType hasPrefix:@"image/jpeg"] || [mimeType hasPrefix:@"image/png"]|| [mimeType hasPrefix:@"image/gif"]|| [mimeType hasPrefix:@"image/jpg"]|| [mimeType hasPrefix:@"image/svg+xml"]|| [mimeType hasPrefix:@"image/vnd.microsoft.icon"]|| [mimeType hasPrefix:@"image/x-icon"]);
}

+ (BOOL)isImageForExtension:(NSString *)extension {
    return [NSString isImageForMimeType:[self mimeTypeForExtension:extension]];
}

@end
